package model;


import entity.History;
import entity.User;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import org.codeforsurvive.utils.MySqlUtil;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author Rohmad Raharjo
 */
public class UserModel extends BaseModel {

    public static final String LOGIN_STATUS = "login_status";
    public static final String LOGGED_USER = "logged_user";

    public UserModel() {
        tableName = "User";
    }

    public Hashtable<String, Object> login(String username, String password) {
        Hashtable<String, Object> result = new Hashtable<>();
        Session session = MySqlUtil.getSessionFactory().openSession();
        Query query = session.createQuery("from " + tableName + " where username = :username and password = md5(:password)");
        query.setParameter("username", username);
        query.setParameter("password", password);
        List rslt = query.list();
        session.close();
        HistoryModel hmodel = new HistoryModel();
        History history = new History();
        history.setTimestamp(new Date());
        if (rslt.size() > 0) {
            result.put(LOGIN_STATUS, true);
            result.put(LOGGED_USER, rslt.get(0));
            history.setUser(((User) result.get(LOGGED_USER)).getId());
            history.setEvent("Successful login");
            

        } else {
            result.put(LOGIN_STATUS, false);
            result.put(LOGGED_USER, new User());
            history.setEvent("Unsuccessful login");
            history.setUser(-1);

        }
        hmodel.save(history);
        

        return result;

    }
    
    public List getUserByPrevilege(String acl)
    {
        return getByColumn("userAccessLevel", acl);
    }

}
